package com.hebtu.helper.modules.sys.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.hebtu.helper.common.utils.LayuiPage;
import com.hebtu.helper.common.utils.Query;
import com.hebtu.helper.modules.sys.service.SysUserRoleService;
import com.hebtu.helper.modules.sys.service.SysUserService;
import com.hebtu.helper.modules.sys.dao.SysUserDao;
import com.hebtu.helper.modules.sys.entity.SysUserEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;



@Service("sysUserService")
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUserEntity> implements SysUserService {

    @Autowired
    private SysUserRoleService sysUserRoleService;

    /**
     * 保存用户
     * 1.保存用户基础信息
     * 2.保存用户对应的角色
     * @param sysUserEntity
     * @return
     */
    @Override
    @Transactional
    public boolean save(SysUserEntity sysUserEntity) {
        if(baseMapper.insert(sysUserEntity)>0) {
            sysUserRoleService.saveAll(sysUserEntity.getUserId(), sysUserEntity.getRoleIds());
            return true;
        }
        return false;
    }

    @Override
    public SysUserEntity selectByUsername(String username) {
        return baseMapper.selectByUsername(username);
    }

    @Override
    public LayuiPage queryPage(Map<String, Object> params) {
        String nickName = (String)params.get("nickName");
                Page<SysUserEntity> page = this.selectPage(
                new Query<SysUserEntity>(params).getPage(),
                new EntityWrapper<SysUserEntity>()
                        .like(StringUtils.isNotBlank(nickName),"nick_name", nickName)
        );

        return new LayuiPage(page.getRecords(), page.getTotal());
    }

    @Override
    public Integer updataStatus(Long userId, boolean status) {
        SysUserEntity sysUserEntity=new SysUserEntity();
        sysUserEntity.setUserId(userId);
        if(status==true)
            sysUserEntity.setState(1);
        else
            sysUserEntity.setState(0);

        return baseMapper.updateById(sysUserEntity);
    }

    /**
     * 修改
     * 1.修改基础信息
     * 2.修改对应的角色
     * @param sysUserEntity
     * @return
     */
    @Override
    public boolean update(SysUserEntity sysUserEntity) {
        if (baseMapper.updateById(sysUserEntity) >= 0) {
            sysUserRoleService.update(sysUserEntity.getUserId(),sysUserEntity.getRoleIds());
            return true;
        }
        return false;
    }

}
